<?php
//For each of my contacts
//Check their RSS feed
//Mix them all in one RSS feed.
if ( defined('ABSPATH') )
	include_once ABSPATH . 'config.php';
else
    include_once '../config.php';

include_once ABSPATH."base/cURL.php";
include_once ABSPATH."base/rss.php";
include_once ABSPATH."base/relationships.php";


$relationships = new Relationships();

if(!isset($_COOKIE["uid"]))
{
		$uid = $_REQUEST["id"];
}
else
{
	$uid = $_COOKIE["uid"];
}

$channel=1;

$rs = $relationships->Get($uid, $channel);


$curl = new cURL(FALSE);

$channel_arr = array();
$items_arr = array();

foreach($rs as $row) {

	$xml = "";
    $xml = $curl->get($row["address"]);
    $dom = new DOMDocument();
    $dom->loadXML($xml);
    $channels = $dom->getElementsByTagName("channel");

    foreach($channels as $channel)
    {
        foreach($channel->childNodes as $elems)
        {
            switch ($elems->nodeName)
            {
                case 'title':
                    $channel_title = $elems->nodeValue;
                    break;
                case 'image':
                    $channel_image = $elems->nodeValue;
	                break;
            }
	  }
    }

    if(!empty($channel_title)) {
        $channel_arr["title"] = $channel_title;
    }
    if(!empty($channel_image)) {
        $channel_arr["image"] = $channel_image;
    }

    $items = $dom->getElementsByTagName("item");
    foreach($items as $item)
    {
        foreach($item->childNodes as $elems)
        {
            switch ($elems->nodeName)
            {
                case 'title':
                    $title = $elems->nodeValue;
                    break;
                case 'pubDate':
                    $pubDate = $elems->nodeValue;
	                break;
                case 'link':
                    $link = $elems->nodeValue;
	                break;
                case 'description':
                    $description = $elems->nodeValue;
                    $description .= "<img src='".$channel_image."'/>";
	                break;	                
            }
	  }
        $item_arr = array();
        if(!empty($title)) {
            $item_arr["title"] = $title;
        }
        if(!empty($pubDate)) {
            $item_arr["pubDate"] = $pubDate;
        }
        if(!empty($link)) {
            $item_arr["link"] = $link;
        }
        if(!empty($description)) {
            $item_arr["description"] = $description;
        }        
        array_push($items_arr, $item_arr);

    }

}

    $rss = new RSS();
    usort($items_arr, 'SortByPubDate');
    $xml = $rss->Get($channel_arr,$items_arr);
    header("content-type","text/xml");
    echo $xml;


function SortByPubDate($a, $b) {
  $a = strtotime($a["pubDate"]);
  $b = strtotime($b["pubDate"]);
	if($a == $b) 
  	{ return 0; }
	
  	return ($a < $b) ? 1 : -1;
}
    

?>